/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "tube.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define DURATION_PER_BIT 10
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
TIM_HandleTypeDef htim2;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_TIM2_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void sendData(char left_end, char middle_left, char middle_right, char right_end, char durationPerBit){
	tube_display(10,10,10,10,4);
	
	HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_1);
	HAL_Delay(durationPerBit);//Start Bit #1
	HAL_Delay(left_end * durationPerBit);//High Level Bit #1
	
	HAL_TIM_PWM_Stop_IT(&htim2, TIM_CHANNEL_1);
	HAL_Delay(9*durationPerBit - left_end*durationPerBit);//Low Level Bit #1
	HAL_Delay(durationPerBit);//Stop Bit #1
	
	HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_1);
	HAL_Delay(durationPerBit);//Start Bit #2
	HAL_Delay(middle_left * durationPerBit);//High Level Bit #2
	
	HAL_TIM_PWM_Stop_IT(&htim2, TIM_CHANNEL_1);
	HAL_Delay(9*durationPerBit - middle_left*durationPerBit);//Low Level Bit #2
	HAL_Delay(durationPerBit);//Stop Bit #2
	
	HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_1);
	HAL_Delay(durationPerBit);//Start Bit #3
	HAL_Delay(middle_right * durationPerBit);//High Level Bit #3
	
	HAL_TIM_PWM_Stop_IT(&htim2, TIM_CHANNEL_1);
	HAL_Delay(9*durationPerBit - middle_right*durationPerBit);//Low Level Bit #3
	HAL_Delay(durationPerBit);//Stop Bit #3
	
	HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_1);
	HAL_Delay(durationPerBit);//Start Bit #4
	HAL_Delay(right_end * durationPerBit);//High Level Bit #4
	
	HAL_TIM_PWM_Stop_IT(&htim2, TIM_CHANNEL_1);
	HAL_Delay(9*durationPerBit - right_end*durationPerBit);//Low Level Bit #4
	HAL_Delay(durationPerBit);//Stop Bit #4
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
	uint8_t transmitting = 0, overallTransmitting = 0;
	uint8_t digit = 1, num_left_end = 10, num_middle_left = 10, num_middle_right = 10, num_right_end = 10;
	uint32_t timeStart, timePause;
	GPIO_PinState input_pin_state_new = GPIO_PIN_RESET, input_pin_state_old = GPIO_PIN_RESET;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM2_Init();
  /* USER CODE BEGIN 2 */
	HAL_TIM_Base_Start_IT(&htim2);

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		input_pin_state_new = HAL_GPIO_ReadPin(GPIOA,P56_Pin);
		if((input_pin_state_new == GPIO_PIN_SET) && (input_pin_state_old == GPIO_PIN_RESET))//0->1
		{
			if(!transmitting){
				timeStart = HAL_GetTick();
				transmitting = 1;
			}
			if(!overallTransmitting){
				overallTransmitting = 1;
				digit = 1;
				num_left_end = 10;
				num_middle_left = 10;
				num_middle_right = 10;
				num_right_end = 10;
			}
			else if(digit>4) digit = 1;
		}
		else if((input_pin_state_new == GPIO_PIN_RESET) && (input_pin_state_old == GPIO_PIN_SET))//1->0
		{
			if(transmitting) timePause = HAL_GetTick();
		}
		else if((input_pin_state_new == GPIO_PIN_RESET) && (input_pin_state_old == GPIO_PIN_RESET))//0->0
		{
			if(transmitting && (HAL_GetTick()-timePause >= DURATION_PER_BIT/2)){
				transmitting = 0;
				if(digit == 1) num_left_end = ((timePause-timeStart)/DURATION_PER_BIT - 1)%10;
				else if(digit == 2) num_middle_left = ((timePause-timeStart)/DURATION_PER_BIT - 1)%10;
				else if(digit == 3) num_middle_right = ((timePause-timeStart)/DURATION_PER_BIT - 1)%10;
				else if(digit == 4) num_right_end = ((timePause-timeStart)/DURATION_PER_BIT - 1)%10;
				digit++;
				if(digit > 4) digit = 5;
			}
			if(overallTransmitting && (HAL_GetTick()-timePause > 5000)) overallTransmitting = 0;
		}
		input_pin_state_old = input_pin_state_new;
		if(overallTransmitting) tube_display(num_left_end,num_middle_left,num_middle_right,num_right_end,4);
		else tube_display(num_left_end,num_middle_left,num_middle_right,num_right_end,0);
	}
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 1;
  RCC_OscInitStruct.PLL.PLLN = 10;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief TIM2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM2_Init(void)
{

  /* USER CODE BEGIN TIM2_Init 0 */

  /* USER CODE END TIM2_Init 0 */

  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_OC_InitTypeDef sConfigOC = {0};

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 4-1;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 1739-1;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_PWM_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 869;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */

  /* USER CODE END TIM2_Init 2 */
  HAL_TIM_MspPostInit(&htim2);

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOC, LED_Pin|E53_18_Pin|E53_19_Pin|E53_17_Pin
                          |WAN_P34_Pin|WAN_P33_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, E53_1_Pin|E53_15_Pin|E53_20_Pin|E53_16_Pin
                          |WAN_P32_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, P58_Pin|WAN_P35_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pins : LED_Pin E53_18_Pin E53_19_Pin E53_17_Pin
                           WAN_P34_Pin WAN_P33_Pin */
  GPIO_InitStruct.Pin = LED_Pin|E53_18_Pin|E53_19_Pin|E53_17_Pin
                          |WAN_P34_Pin|WAN_P33_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

  /*Configure GPIO pins : E53_1_Pin E53_15_Pin E53_20_Pin E53_16_Pin
                           WAN_P32_Pin */
  GPIO_InitStruct.Pin = E53_1_Pin|E53_15_Pin|E53_20_Pin|E53_16_Pin
                          |WAN_P32_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pin : P56_Pin */
  GPIO_InitStruct.Pin = P56_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(P56_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pins : KEY1_Pin KEY2_Pin */
  GPIO_InitStruct.Pin = KEY1_Pin|KEY2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pins : P58_Pin WAN_P35_Pin */
  GPIO_InitStruct.Pin = P58_Pin|WAN_P35_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /* EXTI interrupt init*/
  HAL_NVIC_SetPriority(EXTI3_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(EXTI3_IRQn);

/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if (htim == &htim2)
	{
		HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
	}
}

void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim)
{ 
	if (htim == &htim2)
	{
		HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
	}
}

void HAL_GPIO_EXTI_Callback (uint16_t GPIO_Pin)
{
//	if(GPIO_Pin == KEY1_Pin);
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
